package com.myteam.fugaocrm.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.myteam.fugaocrm.contant.ProjectConstant;
import com.myteam.fugaocrm.modle.FgCompany;
import com.myteam.fugaocrm.modle.FgContractDetail;
import com.myteam.fugaocrm.modle.FgCustomerCompany;
import com.myteam.fugaocrm.modle.FgProject;
import com.myteam.fugaocrm.modle.FgStaff;
import com.myteam.fugaocrm.modle.ReportDTO;
import com.myteam.fugaocrm.service.StaffServiceImpl;
import com.myteam.fugaocrm.sqldb.mapper.FgCompanyMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgContractDetailMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgCustomerCompanyMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgCustomerMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgProjectMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgStaffMapper;


/**
 * 报表管理
 *
 */
@Controller
public class ReportController extends BaseController{
	
	@Resource 
	protected FgProjectMapper fgProjectMapper;
	
	@Resource 
	protected FgStaffMapper fgStaffMapper;
	
	@Resource 
	protected FgCustomerMapper fgCustomerMapper;
	
	@Resource 
	protected StaffServiceImpl staffServiceImpl;
	
	@Resource 
	protected FgCompanyMapper fgCompanyMapper;
	
	@Resource
	protected FgContractDetailMapper fgContractDetailMapper;
	
	@Resource
	protected FgCustomerCompanyMapper fgCustomerCompanyMapper;
	
	/**
	 * 员工报表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("staffReport")
	@ResponseBody
	public ModelAndView staffReport() throws Exception {
		logger.info("进入员工报表页面：staffReport");

        Map<String, Object> attrs = new HashMap<>();
        List<FgStaff> staffList = new ArrayList<FgStaff>();
		staffList = staffServiceImpl.all();
		attrs.put("staffList", staffList);
		
		return new ModelAndView(ProjectConstant.REPORT_STAFF, attrs);
	}
	@RequestMapping("staffReportPage")
	@ResponseBody
	public Object staffReportPage() throws Exception {
		logger.info("查询员工报表分页页面：staffReportPage");

		//如果传参为空 则取第一页数据
    	String currentPage = null==request.getParameter("currentPage") ? "1" : request.getParameter("currentPage");
    	if("".equals(currentPage)){
    		currentPage = "1";
    	}

    	String pageCount = ProjectConstant.EVERY_PAGE_COUNT;
    	Integer startPage =  (Integer.valueOf(currentPage)-1) * Integer.valueOf(pageCount);
    	
		String staffId1 = request.getParameter("staffId");
		String startDate = request.getParameter("startDate");//运维开始时间
        String endDate = request.getParameter("endDate");//运维结束时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
    	
		ReportDTO reportDTO = new ReportDTO();
    	
        if(StringUtils.isNotBlank(startDate)){
        	Date date = sdf.parse(startDate);
        	reportDTO.setStartDate(date);
        }
        if(StringUtils.isNotBlank(endDate)){
        	Date date = sdf.parse(endDate); 
        	reportDTO.setEndDate(date);
        }
        if(StringUtils.isNotBlank(staffId1)){
        	reportDTO.setStaffId(Integer.parseInt(staffId1));
        }
        
        //计数用
        List<FgProject> projectList = fgProjectMapper.findBeforeReportList24(reportDTO);

		reportDTO.setPageCount(pageCount);
		reportDTO.setStartPage(startPage.toString());
        
        Map<String, Object> attrs = new HashMap<>();
        if(StringUtils.isNotBlank(staffId1)||StringUtils.isNotBlank(endDate)||StringUtils.isNotBlank(startDate)){
        	getProjectListReport24(reportDTO, attrs);
        	
        }
        List<FgStaff> staffList = new ArrayList<FgStaff>();
		staffList = staffServiceImpl.all();
		attrs.put("staffList", staffList);
		if(StringUtils.isNotBlank(staffId1)){
			FgStaff staff = fgStaffMapper.selectStaffByStaffId(Integer.parseInt(staffId1));
			attrs.put("staffName", staff.getStaffName());
			attrs.put("staffId", staff.getStaffId());
        }

		//计算公告信息总页数
    	Integer count = Integer.valueOf(projectList.size())/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectList.size())%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		attrs.put("count", count+other);
		
		return attrs;
	}
	
	
	/**
	 * 客户报表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("customerReport")
	@ResponseBody
	public ModelAndView customerReport() throws Exception {
		logger.info("进入客户报表页面：projectReport");
		
        Map<String, Object> attrs = new HashMap<>();
        List<FgCustomerCompany> fgCustomerCompanyList = new ArrayList<FgCustomerCompany>();
        fgCustomerCompanyList = fgCustomerCompanyMapper.all();
		attrs.put("fgCustomerCompanyList", fgCustomerCompanyList);
		return new ModelAndView(ProjectConstant.REPORT_CUSTOMER, attrs);
	}
	
	@RequestMapping("customerReportPage")
	@ResponseBody
	public Object customerReportPage() throws Exception {

		//如果传参为空 则取第一页数据
    	String currentPage = null==request.getParameter("currentPage") ? "1" : request.getParameter("currentPage");
    	if("".equals(currentPage)){
    		currentPage = "1";
    	}

    	String pageCount = ProjectConstant.EVERY_PAGE_COUNT;
    	Integer startPage =  (Integer.valueOf(currentPage)-1) * Integer.valueOf(pageCount);

		ReportDTO reportDTO = new ReportDTO();
		String customerCompanyId = request.getParameter("customerCompanyId");
		String startDate = request.getParameter("startDate");//运维开始时间
        String endDate = request.getParameter("endDate");//运维结束时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        if(StringUtils.isNotBlank(startDate)){
        	Date date = sdf.parse(startDate);
        	reportDTO.setStartDate(date);
        }
        if(StringUtils.isNotBlank(endDate)){
        	Date date = sdf.parse(endDate); 
        	reportDTO.setEndDate(date);
        }
        if(StringUtils.isNotBlank(customerCompanyId)){
        	reportDTO.setCustomerCompanyId(Integer.parseInt(customerCompanyId));
        }
        
        //计数用
        List<FgProject> projectList = fgProjectMapper.findBeforeReportList24(reportDTO);

		reportDTO.setPageCount(pageCount);
		reportDTO.setStartPage(startPage.toString());
        
        Map<String, Object> attrs = new HashMap<>();
        if(StringUtils.isNotBlank(customerCompanyId)||StringUtils.isNotBlank(endDate)||StringUtils.isNotBlank(startDate)){
        	getProjectListReport24(reportDTO, attrs);
        }
        
        List<FgCustomerCompany> fgCustomerCompanyList = new ArrayList<FgCustomerCompany>();
        fgCustomerCompanyList = fgCustomerCompanyMapper.all();
		attrs.put("fgCustomerCompanyList", fgCustomerCompanyList);
		if(StringUtils.isNotBlank(customerCompanyId)){
			FgCustomerCompany fgCustomerCompany = fgCustomerCompanyMapper.selectOne(Integer.parseInt(customerCompanyId));
			attrs.put("customerCompanyId", fgCustomerCompany.getCustomerCompanyId());
			attrs.put("customerCompanyName", fgCustomerCompany.getCustomerCompanyName());
        }
		
		//计算公告信息总页数
    	Integer count = Integer.valueOf(projectList.size())/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectList.size())%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		attrs.put("count", count+other);
		
		return attrs;
	}
	
	/**
	 * 公司报表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("companyReport")
	@ResponseBody
	public ModelAndView companyReport() throws Exception {
		logger.info("进入公司报表页面：projectReport");

        Map<String, Object> attrs = new HashMap<>();
        List<FgCompany> companyList = fgCompanyMapper.all();
		attrs.put("companyList", companyList);
		return new ModelAndView(ProjectConstant.REPORT_COMPANY, attrs);
	}
	@RequestMapping("companyReportPage")
	@ResponseBody
	public Object companyReportPage() throws Exception {
		logger.info("进入公司报表页面：projectReport");

		//如果传参为空 则取第一页数据
    	String currentPage = null==request.getParameter("currentPage") ? "1" : request.getParameter("currentPage");
    	if("".equals(currentPage)){
    		currentPage = "1";
    	}

    	String pageCount = ProjectConstant.EVERY_PAGE_COUNT;
    	Integer startPage =  (Integer.valueOf(currentPage)-1) * Integer.valueOf(pageCount);
    	
		ReportDTO reportDTO = new ReportDTO();
		String companyId = request.getParameter("companyId");
		String startDate = request.getParameter("startDate");//运维开始时间
        String endDate = request.getParameter("endDate");//运维结束时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        if(StringUtils.isNotBlank(startDate)){
        	Date date = sdf.parse(startDate);
        	reportDTO.setStartDate(date);
        }
        if(StringUtils.isNotBlank(endDate)){
        	Date date = sdf.parse(endDate); 
        	reportDTO.setEndDate(date);
        }
        if(StringUtils.isNotBlank(companyId)){
        	reportDTO.setCompanyId(Integer.parseInt(companyId));
        }
        
        //计数用
        List<FgProject> projectList = fgProjectMapper.findBeforeReportList24(reportDTO);

		reportDTO.setPageCount(pageCount);
		reportDTO.setStartPage(startPage.toString());
        
        Map<String, Object> attrs = new HashMap<>();
        if(StringUtils.isNotBlank(companyId)||StringUtils.isNotBlank(endDate)||StringUtils.isNotBlank(startDate)){
        	getProjectListReport24(reportDTO, attrs);
        	
        }
        //查询公司列表
        List<FgCompany> companyList = fgCompanyMapper.all();
		attrs.put("companyList", companyList);
		if(StringUtils.isNotBlank(companyId)){
			FgCompany company = fgCompanyMapper.selectById(Integer.parseInt(companyId));
			attrs.put("companyName", company.getCompanyName());
			attrs.put("companyId", company.getCompanyId());
        }
		
		//计算公告信息总页数
    	Integer count = Integer.valueOf(projectList.size())/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectList.size())%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		attrs.put("count", count+other);
		
		return attrs;
	}
	
	/**
	 * 项目机会报表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("projectReport")
	@ResponseBody
	public ModelAndView projectReport() throws Exception {
		logger.info("进入项目机会报表页面：projectReport");
		
        Map<String, Object> attrs = new HashMap<>();
        getStaff(attrs);
		return new ModelAndView(ProjectConstant.REPORT_PTOJECT, attrs);
	}
	@RequestMapping("projectReportPage")
	@ResponseBody
	public Object projectReportPage() throws Exception {
		logger.info("进入项目机会报表页面：projectReport");
		//登录验证
		String staffIdSession = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffIdSession = request.getSession().getAttribute("staffId").toString();
		}

		//如果传参为空 则取第一页数据
    	String currentPage = null==request.getParameter("currentPage") ? "1" : request.getParameter("currentPage");
    	if("".equals(currentPage)){
    		currentPage = "1";
    	}

    	String pageCount = ProjectConstant.EVERY_PAGE_COUNT;
    	Integer startPage =  (Integer.valueOf(currentPage)-1) * Integer.valueOf(pageCount);
		
		ReportDTO reportDTO = new ReportDTO();
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		String staffId = request.getParameter("staffId");
		String startDate = request.getParameter("startDate");//运维开始时间
        String endDate = request.getParameter("endDate");//运维结束时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        if(StringUtils.isNotBlank(startDate)){
        	Date date = sdf.parse(startDate);
        	reportDTO.setStartDate(date);
        }
        if(StringUtils.isNotBlank(endDate)){
        	Date date = sdf.parse(endDate); 
        	reportDTO.setEndDate(date);
        }
        if(StringUtils.isNotBlank(staffId)){
        	if(!"all".equals(staffId)){
        		reportDTO.setStaffId(Integer.parseInt(staffId));
        	}
        }
        
        //计数用
        List<FgProject> projectList = fgProjectMapper.findBeforeReportList1(reportDTO);

		reportDTO.setPageCount(pageCount);
		reportDTO.setStartPage(startPage.toString());
        
        Map<String, Object> attrs = new HashMap<>();
        if(StringUtils.isNotBlank(staffId)||StringUtils.isNotBlank(endDate)||StringUtils.isNotBlank(startDate)){
        	if("all".equals(staffId)){
        		reportDTO.setStaffId(null);
        	}
        	getProjectListReport1(reportDTO, attrs);
        }else{
        	if("0".equals(permission)||"".equals(permission)){//员工查询本人
        		reportDTO.setStaffId(Integer.parseInt(staffIdSession));
        		getProjectListReport1(reportDTO, attrs);
	    	}else {//其他权限查询全部
	    		reportDTO.setStaffId(null);
	    		getProjectListReport1(reportDTO, attrs);
	    	}
        }
        getStaff(attrs);
        if(StringUtils.isNotBlank(staffId) && !"all".equals(staffId)){
			FgStaff staff = fgStaffMapper.selectStaffByStaffId(Integer.parseInt(staffId));
			attrs.put("staffName", staff.getStaffName());
			attrs.put("staffId", staff.getStaffId());
        }else if(StringUtils.isNotBlank(staffId) && "all".equals(staffId)){
        	attrs.put("staffName", "全部");
        	attrs.put("staffId", "");
        }else if("0".equals(permission)||"".equals(permission)){
        	FgStaff staff = fgStaffMapper.selectStaffByStaffId(Integer.parseInt(staffIdSession));
			attrs.put("staffName", staff.getStaffName());
        	attrs.put("staffId", staffIdSession);
        }else {
        	attrs.put("staffName", "全部");
        	attrs.put("staffId", "");
        }
        if("".equals(permission)){
        	permission="0";
        }
        attrs.put("permission", permission);

		//计算公告信息总页数
    	Integer count = Integer.valueOf(projectList.size())/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectList.size())%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		attrs.put("count", count+other);
		
		return attrs;
	}
	
	/**
	 * 未回款统计表
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("notPaymentReport")
	@ResponseBody
	public ModelAndView notPaymentReport() throws Exception {
		logger.info("进入项目未回款统计报表页面：notPaymentReport");
		
        Map<String, Object> attrs = new HashMap<>();
        getStaff(attrs);
		return new ModelAndView(ProjectConstant.REPORT_NOT_PAYMENT, attrs);
	}
	@RequestMapping("notPaymentReportPage")
	@ResponseBody
	public Object notPaymentReportPage() throws Exception {
		logger.info("进入项目未回款统计报表页面：notPaymentReport");
		//登录验证
		String staffIdSession = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffIdSession = request.getSession().getAttribute("staffId").toString();
		}

		//如果传参为空 则取第一页数据
    	String currentPage = null==request.getParameter("currentPage") ? "1" : request.getParameter("currentPage");
    	if("".equals(currentPage)){
    		currentPage = "1";
    	}

    	String pageCount = ProjectConstant.EVERY_PAGE_COUNT;
    	Integer startPage =  (Integer.valueOf(currentPage)-1) * Integer.valueOf(pageCount);
		
		FgStaff staff = fgStaffMapper.selectStaffByStaffId(Integer.parseInt(staffIdSession));
		
		ReportDTO reportDTO = new ReportDTO();
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		String staffId = request.getParameter("staffId");
		String startDate = request.getParameter("startDate");//运维开始时间
        String endDate = request.getParameter("endDate");//运维结束时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        if(StringUtils.isNotBlank(startDate)){
        	Date date = sdf.parse(startDate);
        	reportDTO.setStartDate(date);
        }
        if(StringUtils.isNotBlank(endDate)){
        	Date date = sdf.parse(endDate); 
        	reportDTO.setEndDate(date);
        }
        if(StringUtils.isNotBlank(staffId) && !"all".equals(staffId)){
    		reportDTO.setStaffId(Integer.parseInt(staffId));
        }else {
        	reportDTO.setStaffId(null);
        }
        
		reportDTO.setPageCount(pageCount);
		reportDTO.setStartPage(startPage.toString());
        
        Map<String, Object> attrs = new HashMap<>();
        List<FgProject> projectList = getProjectListReportByNotPayment(reportDTO, attrs);
        
        getStaff(attrs);
        
        if(StringUtils.isNotBlank(staffId) && !"all".equals(staffId)){
			attrs.put("staffName", staff.getStaffName());
			attrs.put("staffId", staff.getStaffId());
        }else if(StringUtils.isNotBlank(staffId) && "all".equals(staffId)){
        	attrs.put("staffName", "全部");
        	attrs.put("staffId", "");
        }else if("0".equals(permission) || "".equals(permission)){
			attrs.put("staffName", staff.getStaffName());
        	attrs.put("staffId", staffIdSession);
        }else {
        	attrs.put("staffName", "全部");
        	attrs.put("staffId", "");
        }
        if("".equals(permission)){
        	permission="0";
        }
        attrs.put("permission", permission);

		//计算公告信息总页数
    	Integer count = Integer.valueOf(projectList.size())/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectList.size())%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		attrs.put("count", count+other);
	
		return attrs;
	}
	
	/**
	 * 未回款统计表
	 * @param reportDTO
	 * @param attrs
	 */
	private List<FgProject> getProjectListReportByNotPayment(ReportDTO reportDTO, Map<String, Object> attrs){
		List<FgProject> projectList = fgProjectMapper.findBeforeReportList2(reportDTO);
		
		//业绩加总值
    	BigDecimal count = BigDecimal.ZERO;
		
		if(null != projectList && !projectList.isEmpty()) {
	    			
    		for(FgProject p : projectList) { //循环项目
    			
    			FgContractDetail detail = fgContractDetailMapper.selectNotPayment(p.getProjectId());

    			if(detail == null) {
    				detail = new FgContractDetail();
    				detail.setBillingRate("0");
    				detail.setBillingMoney("0");
    				detail.setPaymentRate("0");
    				detail.setPaymentMoney("0");
    			}else {
    				if(detail.getBillingRate() == null) {
        				detail.setBillingRate("0");
        			}
        			if(detail.getBillingMoney() == null) {
        				detail.setBillingMoney("0");
        			}
        			if(detail.getPaymentRate() == null) {
        				detail.setPaymentRate("0");
        			}
        			if(detail.getPaymentMoney() == null) {
        				detail.setPaymentMoney("0");
        			}
    			}
    			
    			p.setBillingRate(detail.getBillingRate());
    			p.setBillingMoney(new BigDecimal(detail.getBillingMoney()));

    			p.setPaymentRate(new BigDecimal(100).subtract(new BigDecimal(detail.getPaymentRate())).toString());
    			p.setPaymentMoney(new BigDecimal(p.getOffer()).subtract(new BigDecimal(detail.getPaymentMoney())));
    			
    			//业绩加总值
    	    	count.add(p.getPaymentMoney());
    	    	
    	    	//签约时间转换
    	    	if(p.getSignDate() != null) {
    				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    				p.setSignDateStr(sdf.format(p.getSignDate()));
    	    	}
    		}
		}
		attrs.put("projectList", projectList);
    	attrs.put("count", count);
		
		return projectList;
	}
	
	private void getProjectListReport1(ReportDTO reportDTO, Map<String, Object> attrs){
		List<FgProject> projectList = fgProjectMapper.findBeforeReportList1(reportDTO);
    	//业绩加总值
    	BigDecimal count = BigDecimal.ZERO;
    	if(null != projectList && !projectList.isEmpty()){
    		for(FgProject p : projectList){
    			if(StringUtils.isNotBlank(p.getOffer())){
    				count = count.add(new BigDecimal(p.getOffer()));
    			}
    		}
    	}
    	attrs.put("projectList", projectList);
    	attrs.put("count", count);
	}
	
	private void getProjectListReport24(ReportDTO reportDTO, Map<String, Object> attrs){
		List<FgProject> projectList = fgProjectMapper.findBeforeReportList24(reportDTO);
    	//业绩加总值
    	BigDecimal count = BigDecimal.ZERO;
    	if(null != projectList && !projectList.isEmpty()){
    		for(FgProject p : projectList){
    			if(StringUtils.isNotBlank(p.getOffer())){
    				count = count.add(new BigDecimal(p.getOffer()));
    			}
    		}
    	}

    	attrs.put("projectList", projectList);
    	attrs.put("sumCount", count);
	}
	
	private void getStaff(Map<String, Object> attrs){
		List<FgStaff> staffList = new ArrayList<FgStaff>();
		staffList = staffServiceImpl.all();
		attrs.put("staffList", staffList);
	}
	
}
